
package com.feib.soeasy.dao.hibernate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.feib.soeasy.dao.FormatDefinitionDao;
import com.feib.soeasy.model.FormatDefinition;
import com.feib.soeasy.model.Group;
import com.feib.soeasy.pagination.PaginatedList;


/**
 * @title (#)FormatDefinitionHibernateDao.java<br>
 * @description 帳單匯入格式(收款類別)Dao 實作<br>
 * @author Jimmy Liu<br>
 * @version 1.0.0 2010/11/25
 * @copyright Far Eastern International Bank Copyright (c) 2010<br>
 * @2010/11/20 create by Jimmy Liu<br>
 */
@Repository("formatDefinitionDao")
public class FormatDefinitionHibernateDao extends BaseHibernateDao<FormatDefinition, Long> implements FormatDefinitionDao {
    
    /* (non-Javadoc)
     * @see com.feib.soeasy.dao.hibernate.BaseHibernateDao#findByExample(java.lang.Object)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<FormatDefinition> findByExample(FormatDefinition formatDefinition) {
        DetachedCriteria criteria = createDetachedCriteriaByFormatDefinition(formatDefinition);
        return this.getHibernateTemplate().findByCriteria(criteria);
    }
    
    @SuppressWarnings("unchecked")
    @Override
    public PaginatedList<FormatDefinition> queryPaginationByFormatDefinition(FormatDefinition formatDefinition, PaginatedList<FormatDefinition> paginationConfig)
    {

        PaginatedList<FormatDefinition> result = new PaginatedList<FormatDefinition>();
        result.setPageSize(paginationConfig.getPageSize());
        result.setPageNumber(paginationConfig.getPageNumber());
        result.setSortCriterion(paginationConfig.getSortCriterion());
        result.setSortDirection(paginationConfig.getSortDirection());
        
        result.setFullListSize(super.countByDetachedCriteria(createDetachedCriteriaByFormatDefinition(formatDefinition)));

        // 筆數大於0
        if (0 < result.getFullListSize())
        {
            DetachedCriteria criteria = createDetachedCriteriaByFormatDefinition(formatDefinition);

            //排序
            if (null != paginationConfig.getSortCriterion())
            {
                // 由小到大
                if (PaginatedList.SORT_DIRECTION_ASC == paginationConfig.getSortDirection())
                {
                    criteria.addOrder(Order.asc(paginationConfig.getSortCriterion()));
                }
                else // 由大到小
                {
                    criteria.addOrder(Order.asc(paginationConfig.getSortCriterion()));
                }
            }


            int maxResults = result.getPageSize(); //the maximum number of results
            int firstResult = result.getFirstIndexForCurrentPage();  //the first result to retrieve, numbered from 0
            result.setPaginatedList(this.getHibernateTemplate().findByCriteria(criteria, firstResult, maxResults));
        }

        return result;
    }
    
    protected DetachedCriteria createDetachedCriteriaByFormatDefinition(FormatDefinition entity)
    {
        DetachedCriteria criteria = DetachedCriteria.forClass(this.getPersistentClass());
        criteria.setResultTransformer(DetachedCriteria.DISTINCT_ROOT_ENTITY);

        Example example = Example.create(entity);
        example.enableLike(MatchMode.START);
        example.excludeZeroes();
        criteria.add(example);

        // 屬於哪一個群組
        if (null != entity.getGroup())
        {
            DetachedCriteria detachedCriteria = criteria.createCriteria("group");

            // PK 有值，需加入為查詢條件
            if (null != entity.getGroup().getGroupPk())
            {
                detachedCriteria.add(Restrictions.idEq(entity.getGroup().getGroupPk()));
            }

            // Group 其他查詢條件
            Example e = Example.create(entity.getGroup());
            e.enableLike(MatchMode.START);
            e.excludeZeroes();
            detachedCriteria.add(e);
        }
        return criteria;
    }

    /* (non-Javadoc)
     * @see com.feib.soeasy.dao.FormatDefinitionDao#countFormatDefinitionByGroup(com.feib.soeasy.model.Group)
     */
    @Override
    public int countFormatDefinitionByGroup(Group group) {

        DetachedCriteria criteria = DetachedCriteria.forClass(this.getPersistentClass());
        criteria.setResultTransformer(DetachedCriteria.DISTINCT_ROOT_ENTITY);

        DetachedCriteria detachedCriteria = criteria.createCriteria("group");
        detachedCriteria.add(Restrictions.idEq(group.getGroupPk()));
        

        criteria.add(Restrictions.eq("batchUsed", Boolean.FALSE)); // 排除系統自己新增的設定檔

        return countByDetachedCriteria(criteria);
    }

    /* (non-Javadoc)
     * @see com.feib.soeasy.dao.FormatDefinitionDao#deleteByGroup(com.feib.soeasy.model.Group)
     */
    @Override
    public void deleteByGroup(Group group) {
        DetachedCriteria criteria = DetachedCriteria.forClass(this.getPersistentClass());
        criteria.setResultTransformer(DetachedCriteria.DISTINCT_ROOT_ENTITY);

        DetachedCriteria detachedCriteria = criteria.createCriteria("group");
        detachedCriteria.add(Restrictions.idEq(group.getGroupPk()));
        
        this.getHibernateTemplate().deleteAll(this.getHibernateTemplate().findByCriteria(criteria));
        
//        StringBuffer hql = new StringBuffer();
//        hql.append("delete ColumnDefinition as c inner join fetch c.formatDefinition f ");
//        hql.append("where f.group = :group ");
//        Query query = getSession().createQuery(hql.toString());
//        query.setParameter("group", group);
//        query.executeUpdate();
//        
//        hql = new StringBuffer();
//        hql.append("delete CommissionCodeTable ");
//        hql.append("where formatDefinition.group = :group ");
//        query = getSession().createQuery(hql.toString());
//        query.setParameter("group", group);
//        query.executeUpdate();
//        
//        hql = new StringBuffer();
//        hql.append("delete FormatDefinition ");
//        hql.append("where group = :group ");
//        query = getSession().createQuery(hql.toString());
//        query.setParameter("group", group);
//        query.executeUpdate();
    }
}
